import { pageListLgExtrasDict, getLgExtrasDictById, updateLgExtrasDict, deleteLgExtrasDict } from '@/services/rule/speical_charges_api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, Input, message, Modal } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import AddForm from './components/AddForm';
import { LgExtrasDictVO } from "../constants"



const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [loading, setLoading] = useState(false);
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<LgExtrasDictVO>();
  const [selectedRowsState, setSelectedRows] = useState<LgExtrasDictVO[]>([]);
  const [editRow, setEditRow] = useState<LgExtrasDictVO>();


  const getCustomerInfo = async (id: string) => {
    try {
      const response = await getLgExtrasDictById(id);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          throw new Error(response.msg);
        }
      }
      setEditRow(response.data);
    } catch (error) {
      message.error(intl.formatMessage({ id: "request.error.retry" }));
      return false;
    }
  };


  const queryPageData = async (pageParams: any) => {
    try {
      const response = await pageListLgExtrasDict(pageParams);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
        }
      }
      return response.data;
    } catch (error) {
      console.error(error);
      message.error(intl.formatMessage({ id: "request.error.retry" }));
    }
  };


  const pageQueryCustomer = async (params, sorter, filter) => {
    // 表单搜索项会从 params 传入，传递给后端接口。
    // console.log(params, sorter, filter);
    // const { current, pageSize, customerCode, customerName, customerStatus } = params
    // let queryParams = {};
    // if (current !== undefined) queryParams.current = current;
    // if (pageSize !== undefined) queryParams.pageSize = pageSize;
    // if (customerCode !== undefined) queryParams.likeCode = customerCode;
    // if (customerName !== undefined) queryParams.likeName = customerName;
    // if (customerStatus !== undefined) queryParams.status = Number(customerStatus);
    return await queryPageData(params);
  }

  const makeActive = (record: LgExtrasDictVO) => {
    Modal.confirm({
      title: intl.formatMessage({ id: 'pages.shippingAddress.confirm.title' }),
      content: intl.formatMessage({ id: 'pages.shippingAddress.confirm.content' }),
      okText: intl.formatMessage({ id: 'pages.confirm' }),
      cancelText: intl.formatMessage({ id: 'pages.cancel' }),
      onOk: async () => {
        const hide = message.loading(intl.formatMessage({ id: 'pages.processing' }));
        try {
          const response = await deleteLgExtrasDict(record.id);
          if (response.code != 0) {
            if (!response.msg) {
              throw new Error(intl.formatMessage({ id: "request.error.create" }));
            } else {
              message.error(response.msg);
              return false;
            }
          }
          hide();
          message.success(intl.formatMessage({ id: 'pages.shippingAddress.delete.success' }));
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } catch (error) {
          console.error(error);
          hide();
          message.error(intl.formatMessage({ id: 'request.error.retry' }));
        }
      },
    });
  }

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<LgExtrasDictVO>[] = [
  {
    title: (
      <FormattedMessage
        id="pages.extras.ruleName"
        defaultMessage="Additional fee name"
      />
    ),
    dataIndex: 'lgExtrasName',
    key: 'lgExtrasName',
  },
  {
    title: (
      <FormattedMessage
        id="pages.extras.ruleCode"
        defaultMessage="Additional fee Code"
      />
    ),
    dataIndex: 'lgExtrasCode',
    key: 'lgExtrasCode',
  },
  {
    title: (
      <FormattedMessage
        id="pages.extras.serviceProvider"
        defaultMessage="Service Provider"
      />
    ),
    dataIndex: 'serviceProvider',
    key: 'serviceProvider',
  },
  {
    title: (
      <FormattedMessage
        id="pages.extras.ruleDescription"
        defaultMessage="Additional fee Description"
      />
    ),
    dataIndex: 'extrasDescription',
    key: 'extrasDescription',
  },
  {
    title: (
      <FormattedMessage
        id="pages.extras.updater"
        defaultMessage="Updater"
      />
    ),
    dataIndex: 'updater',
    key: 'updater',
    search: false,
  },
  {
    title: (
      <FormattedMessage
        id="pages.extras.updateTime"
        defaultMessage="Update Time"
      />
    ),
    dataIndex: 'updateTime',
    key: 'updateTime',
    valueType: 'dateTime', // 使用 dateTime 类型显示时间
    sorter: true, // 允许排序
    search: false,
  },
  // {
  //   title: (
  //     <FormattedMessage
  //       id="pages.extras.creator"
  //       defaultMessage="Creator"
  //     />
  //   ),
  //   dataIndex: 'creator',
  //   key: 'creator',
  // },
  
  {
    title: (
      <FormattedMessage
        id="pages.operating"
        defaultMessage="Operating"
      />
    ),
    dataIndex: 'option',
    valueType: 'option',
    fixed: 'right',
    // width: 120,
    render: (_, record) => [
      <a
        key="edit"
        onClick={async () => {          
          setCurrentRow(record);
          handleUpdateModalOpen(true); // 打开编辑弹窗
        }}
      >
        <FormattedMessage
          id="pages.edit"
          defaultMessage="Edit"
        />
      </a>,
      <a
        key="delete"
        onClick={() => {
          makeActive(record);
          setCurrentRow(record);
        }}
      >
        <FormattedMessage
          id="pages.delete"
          defaultMessage="Delete"
        />
      </a>,
    ],
  },
];

  return (
    <PageContainer title={false}>
      <ProTable<LgExtrasDictVO, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.extras.list',
          defaultMessage: 'Additional fee List',
        })}
        actionRef={actionRef}
        loading={loading}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              //新建
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> {" "}
            <FormattedMessage id="pages.extras.create" defaultMessage="New" />
          </Button>,
        ]}
        request={pageQueryCustomer}
        columns={columns}
      />


      <AddForm
        // width="40%"
        visible={createModalOpen}
        // onOpenChange={handleModalOpen}
        onCancel={async () => { handleModalOpen(false) }}
        onSuccess={function (): void {
          handleModalOpen(false)
          setCurrentRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      >
      </AddForm>

      <AddForm
        visible={updateModalOpen}
        values={currentRow}
        onCancel={async () => {
          handleUpdateModalOpen(false);
          setCurrentRow(undefined);
          setEditRow(undefined);
        }}
        onSuccess={function (): void {
          handleUpdateModalOpen(false)
          setCurrentRow(undefined);
          setEditRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      >
      </AddForm>
    </PageContainer>
  );
};

export default TableList;
